package me.flyray.bsin.server.utils;

import com.plexpt.chatgpt.entity.chat.Message;

import java.util.*;

public class ChatContexStorage {

    private static Map<String, List<Message>> context = new HashMap();

    public ChatContexStorage() {
    }

    public static List<Message> get(String id) {
        List<Message> messages = (List) context.get(id);
        if (messages == null) {
            messages = new ArrayList();
            context.put(id, messages);
        }

        return (List) messages;
    }

    public static void add(String id, String msg) {
        Message message = Message.builder().content(msg).build();
        add(id, message);
    }

    public static void add(String id, Message message) {
        List<Message> messages = (List) context.get(id);
        if (messages == null) {
            messages = new ArrayList();
            context.put(id, messages);
        }
        ((List) messages).add(message);
    }

    public static void add(String id, Message message, int limit) {
        List<Message> messages = (List) context.get(id);
        if (messages == null) {
            messages = new ArrayList();
            context.put(id, messages);
        }
        ((List) messages).add(message);
        int messageSize = messages.size();
        if (messageSize > (limit + 1)) {
            for (int i = 0; i < (messageSize - limit - 1); i++) {
                messages.remove(1);
            }
        }
    }

    public static void remove(String id) {
        context.remove(id);
    }

    // 移除最后加进去的元素
    public static void pop(String id) {
        List<Message> messages = (List) context.get(id);
        if (messages != null) {
            int size = messages.size();
            System.out.println("size: " + size);
            System.out.println("remove  " + messages.get(size - 1).toString());
            messages.remove(size - 1);
        }
    }
}

